package cn.wolfcode.wolf2w.gateway.filter;

import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.utils.RedisKeys;
import cn.wolfcode.wolf2w.gateway.util.Md5Util;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class SignFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        Map<String, Object> map = new HashMap<>();
        for (String key : queryParams.keySet()) {
            if ("sign".equals(key)) {
                continue;
            }
            List<String> list = queryParams.get(key);
            StringBuffer sb = new StringBuffer();
            for (String s : list) {
                sb.append(s);
            }
            String value = sb.toString(); //和servlet体系中参数一样的value
            map.put(key, value);
        }
        String sign_server = Md5Util.signatures(map); //服务端签名
        String sign_client = queryParams.getFirst("sign");

        //这个if是为了测试加的，因为我们的前端接口只有test2添加了加密的sign
        if (!exchange.getRequest().getURI().getPath().contains("test2")) {
            return chain.filter(exchange);
        }

        if (sign_client != null && sign_client.equals(sign_server)) {
            //放行
            String timestamp = exchange.getRequest().getQueryParams().getFirst("timestamp");
            Long client_time = Long.valueOf(timestamp);
            Long server_time = System.currentTimeMillis();
//            if ((server_time - timestamp) >20000)
            return chain.filter(exchange);
        } else {
            R<Object> r = R.fail(500, "参数被篡改");
            String jsonString = JSON.toJSONString(r);
            HttpHeaders headers = exchange.getResponse().getHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(jsonString.getBytes(StandardCharsets.UTF_8));
            return exchange.getResponse().writeWith(Mono.just(dataBuffer));
        }
    }
}
